package com.bdqn.dao;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileOutputStream;
import java.io.IOException;

public class studentAdd {
    public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException, TransformerException {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        //从DOM工厂获得DOM解析器
        DocumentBuilder db = dbf.newDocumentBuilder();
        //解析XML文档，得到一个Document对象，即DOM树
        Document doc = db.parse("ch02jd/src/ppp.xml");  //收藏信息.xml为保存手机收藏信息的xml文档
        //创建brand节点
        Element brandElement = doc.createElement("student");
        brandElement.setAttribute("id", "3");
        ///创建Type节点
        brandElement.setAttribute("name", "邱平毅");

        brandElement.setAttribute("course", "计算机");
        brandElement.setAttribute("score", "89");
        //添加父子关系
        Element phoneElement = (Element) doc.getElementsByTagName("scores").item(0);
        phoneElement.appendChild(brandElement);
        //保存XML文件
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource domSource = new DOMSource(doc);
        //设置编码类型
        transformer.setOutputProperty(OutputKeys.ENCODING, "gb2312");
        StreamResult result = new StreamResult(new FileOutputStream("ch02jd/src/ppp.xml"));
        //把DOM树转换为xml文件
        transformer.transform(domSource, result);
    }
}
